<template>
  <div class="app-container">
    <div class="filter-container">
      <SearchOptionClass :class-id="listQuery.class_id" @setSearchClassId="searchClassId" />
      <SearchOptionXuanxiuCourse :class-id="listQuery.course_id" @setSearchCourseId="searchCourseId" />
      <el-select v-model="listQuery.status" placeholder="状态" clearable class="filter-item" style="width: 130px">
        <el-option v-for="(value,key) in statusOptions" :key="key" :label="value" :value="key" />
      </el-select>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :header-cell-style="{background:'#ccc',color:'black'}"
      :data="list"
      border
      stripe
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="ID" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="课程名称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.courseInfo.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="班级简称" align="center">
        <template slot-scope="{row}">
          <span>{{ row.short_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="授课老师" align="center">
        <template slot-scope="{row}">
          <p v-for="(item,index) in row.teacherInfo" :key="index" style="margin:0">{{ item }}</p>
        </template>
      </el-table-column>
      <el-table-column label="学分" align="center">
        <template slot-scope="{row}">
          <span>{{ row.score }}</span>
        </template>
      </el-table-column>
      <el-table-column label="课程容量" align="center">
        <template slot-scope="{row}">
          <span>{{ row.min_num+" - "+row.max_num }}</span>
        </template>
      </el-table-column>
      <el-table-column label="选修范围" align="center">
        <template slot-scope="{row}">
          <el-link @click="jumpDetailUser(row.id,1)">{{ row.userList.sum }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="选课学生" align="center">
        <template slot-scope="{row}">
          <el-link @click="jumpDetailUser(row.id,2)">{{ row.userList.xuanke }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="候补学生" align="center">
        <template slot-scope="{row}">
          <span>{{ getHoubu(row) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="未选学生" align="center">
        <template slot-scope="{row}">
          <span>{{ row.userList.sum - row.userList.xuanke }}</span>
        </template>
      </el-table-column>

      <el-table-column label="第一轮开始时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.one_stime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="上课时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.course_stime }}</span>
          <span>{{ row.course_etime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="{row}">
          <span>{{ statusOptions[row.status] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button type="danger" size="mini" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="110px" style="width: 400px; margin-left:50px;">
        <el-form-item v-model="temp.xuanxiu_course_id" label="课程名称" prop="xuanxiu_course_id" class="filter-item">
          <SearchOptionXuanxiuCourse :course-id="temp.xuanxiu_course_id" @setSearchCourseId="updateCourseId" />
        </el-form-item>
        <el-form-item label="上课班级" prop="class_ids">
          <el-select v-model="temp.class_ids" class="filter-item" multiple filterable>
            <el-option v-for="(value,key) in classList" :key="key" :label="value.name" :value="value.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="班级简称" prop="short_name">
          <el-input v-model="temp.short_name" />
        </el-form-item>
        <el-form-item label="授课老师" prop="teacher_ids">
          <el-select v-model="temp.teacher_ids" prop="semester" class="filter-item" multiple filterable>
            <el-option v-for="(value,key) in teacherList" :key="key" :label="value.name" :value="value.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="学分">
          <el-input-number v-model="temp.score" :min="0" />
        </el-form-item>
        <el-form-item label="最小人数">
          <el-input-number v-model="temp.min_num" :min="0" />
        </el-form-item>
        <el-form-item label="最大人数">
          <el-input-number v-model="temp.max_num" :min="0" />
        </el-form-item>
        <el-form-item label="候补人数">
          <el-input-number v-model="temp.sub_num" :min="0" />
        </el-form-item>
        <el-form-item label="上课开始时间" prop="course_stime">
          <div class="block">
            <el-date-picker
              v-model="temp.course_stime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="开始日期"
            />
          </div>
        </el-form-item>
        <el-form-item label="上课结束时间" prop="course_etime">
          <div class="block">
            <el-date-picker
              v-model="temp.course_etime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="结束日期"
            />
          </div>
        </el-form-item>
        <el-form-item label="第一轮开始时间" prop="one_stime">
          <div class="block">
            <el-date-picker
              v-model="temp.one_stime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="结束日期"
            />
          </div>
        </el-form-item>
        <el-form-item label="第一轮结束时间" prop="one_etime">
          <div class="block">
            <el-date-picker
              v-model="temp.one_etime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="结束日期"
            />
          </div>
        </el-form-item>
        <el-form-item label="第二轮开始时间" prop="two_stime">
          <div class="block">
            <el-date-picker
              v-model="temp.two_stime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="结束日期"
            />
          </div>
        </el-form-item>
        <el-form-item label="第二轮结束时间" prop="two_etime">
          <div class="block">
            <el-date-picker
              v-model="temp.two_etime"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="结束日期"
            />
          </div>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="temp.status" class="filter-item" filterable>
            <el-option v-for="(value,key) in statusOptions" :key="key" :label="value" :value="key" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { timetablePage, timetableUpdate, timetableDelete } from '@/api/xuanxiu'
import waves from '@/directive/waves' // waves directive
import { notifySuccess, my_confirm, listQueryFilter } from '@/utils/tool'
import SearchOptionXuanxiuCourse from '@/components/SearchOption/xuanxiucourse'
import SearchOptionClass from '@/components/SearchOption/class'
import Pagination from '@/components/Pagination'
import { classPage } from '@/api/class'
import { userPage } from '@/api/user'

export default {
  name: 'XuanxiuTimetable',
  components: { SearchOptionXuanxiuCourse, Pagination, SearchOptionClass },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        querySort: '-id',
        class_ids: null,
        teacher_ids: null,
        status: null
      },
      classListQuery: {
        page: 1,
        limit: 1000
      },
      teacherListQuery: {
        page: 1,
        limit: 1000,
        type: 1
      },
      statusOptions: {
        1: '未发布',
        2: '已发布',
        3: '暂停',
        4: '已取消',
        5: '已开课'
      },
      temp: {
        id: null,
        xuanxiu_course_id: null,
        class_ids: '',
        short_name: '',
        teacher_ids: '',
        score: 0,
        max_num: 0,
        min_num: 0,
        sub_num: 0,
        course_stime: '',
        course_etime: '',
        one_stime: '',
        one_etime: '',
        two_stime: '',
        two_etime: '',
        status: '1'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },
      rules: {
        xuanxiu_course_id: [{ required: true, message: '课程名称必填', trigger: 'change' }],
        class_ids: [{ required: true, message: '开课班级必填', trigger: 'change' }],
        short_name: [{ required: true, message: '开课班级必填', trigger: 'change' }],
        teacher_ids: [{ required: true, message: '授课老师必填', trigger: 'change' }],
        course_stime: [{ required: true, message: '上课开始时间必填', trigger: 'change' }],
        course_etime: [{ required: true, message: '上课结束时间必填', trigger: 'change' }],
        one_stime: [{ required: true, message: '第一轮开始时间必填', trigger: 'change' }],
        one_etime: [{ required: true, message: '第一轮结束时间必填', trigger: 'change' }],
        status: [{ required: true, message: '状态必填', trigger: 'change' }]
      },
      classList: [],
      teacherList: [],
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getTeacherList() {
      this.teacherListQuery = listQueryFilter(this.teacherListQuery)
      userPage(this.teacherListQuery).then(response => {
        this.teacherList = response.data
      })
    },
    getClassList() {
      this.classListQuery = listQueryFilter(this.classListQuery)
      classPage(this.classListQuery).then(response => {
        this.classList = response.data
      })
    },

    getList() {
      this.listLoading = true
      this.listQuery = listQueryFilter(this.listQuery)
      timetablePage(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.page
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetTemp() {
      this.temp = {
        xuanxiu_course_id: null,
        class_ids: '',
        short_name: '',
        teacher_ids: '',
        score: 0,
        max_num: 0,
        min_num: 0,
        sub_num: 0,
        course_stime: '',
        course_etime: '',
        one_stime: '',
        one_etime: '',
        two_stime: '',
        two_etime: '',
        status: '1'
      }
    },
    handleCreate() {
      this.getClassList()
      this.getTeacherList()
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const creatTempData = JSON.parse(JSON.stringify(this.temp))
          creatTempData.class_ids.push(' ')
          creatTempData.class_ids.unshift(' ')
          creatTempData.class_ids = creatTempData.class_ids.join(',')
          creatTempData.class_ids = creatTempData.class_ids.replace(/ /g, '')
          creatTempData.teacher_ids.push(' ')
          creatTempData.teacher_ids.unshift(' ')
          creatTempData.teacher_ids = creatTempData.teacher_ids.join(',')
          creatTempData.teacher_ids = creatTempData.teacher_ids.replace(/ /g, '')
          delete creatTempData.courseInfo
          timetableUpdate(creatTempData).then(response => {
            this.dialogFormVisible = false
            notifySuccess(this, '创建成功')
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      this.getClassList()
      this.getTeacherList()
      this.temp = Object.assign({}, row)
      this.temp.class_ids = row.class_ids.split(',').filter(item => { return item })
      this.temp.teacher_ids = row.teacher_ids.split(',').filter(item => { return item })
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = JSON.parse(JSON.stringify(this.temp))
          tempData.class_ids.push(' ')
          tempData.class_ids.unshift(' ')
          tempData.class_ids = tempData.class_ids.join(',')
          tempData.class_ids = tempData.class_ids.replace(/ /g, '')
          tempData.teacher_ids.push(' ')
          tempData.teacher_ids.unshift(' ')
          tempData.teacher_ids = tempData.teacher_ids.join(',')
          tempData.teacher_ids = tempData.teacher_ids.replace(/ /g, '')
          delete tempData.timetableUserInfo
          delete tempData.courseInfo
          delete tempData.schoolClassInfo
          delete tempData.teacherInfo
          timetableUpdate(tempData).then(response => {
            this.dialogFormVisible = false
            notifySuccess(this, '修改成功')
            this.getList()
          })
        }
      })
    },
    handleDelete(row, index) {
      my_confirm(this, () => {
        timetableDelete({ id: row.id }).then(() => {
          this.list.splice(index, 1)
          this.dialogFormVisible = false
          notifySuccess(this, '删除成功')
        })
      })
    },
    jumpDetailUser(xuanxiu_timetable_id, type) {
      if (type === 1) {
        this.$router.push({
          path: '/xuanxiu/timetableUser',
          query: {
            xuanxiu_timetable_id: xuanxiu_timetable_id
          }
        })
      } else if (type === 2) {
        this.$router.push({
          path: '/xuanxiu/timetableUser',
          query: {
            id: xuanxiu_timetable_id,
            tab: 'second'
          }
        })
      }
    },
    getHoubu: function(row) {
      var houbuNum = Number(row.userList.xuanke) - Number(row.max_num)
      if (houbuNum < 0) {
        return 0 + '/' + row.sub_num
      } else {
        return houbuNum + '/' + row.sub_num
      }
    },
    searchClassId: function(data) {
      this.listQuery.class_ids = data.classId
    },
    searchUserId: function(data) {
      this.listQuery.teacher_ids = data.userId
    },
    searchCourseId: function(data) {
      this.listQuery.xuanxiu_course_id = data.courseId
    },
    updateCourseId: function(data) {
      console.log('data.courseId is', data.courseId)
      this.temp.xuanxiu_course_id = data.courseId
    }
  }
}
</script>
